// https://leetcode.cn/problems/combination-sum-iv/
// Created by ade on 2022/11/23.
// 给你一个由 不同 整数组成的数组 nums ，和一个目标整数 target 。请你从 nums 中找出并返回总和为 target 的元素组合的个数。
#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

class Solution {
public:
    // 暴力会超时
    int count = 0, len = 0;

    int combinationSum41(vector<int> &nums, int target) {
        sort(nums.begin(), nums.end());
        len = nums.size();

        for (int i = 0; i < len; i++) {
            dfs(nums, target, nums[i]);
        }
        return count;
    }

    void dfs(vector<int> &nums, int &target, int total) {
        if (total > target) {
            return;
        }
        if (total == target) {
            count++;
            return;
        }
        for (int i = 0; i < len; i++) {
            if (total + nums[i] > target) break;
            dfs(nums, target, total + nums[i]);
        }
    }

    int combinationSum4(vector<int> &nums, int target) {
        vector<int> dp(target + 1);
        dp[0] = 1;
        for (int i = 1; i <= target; i++) {
            for (auto &num:nums) {
                if (num <= i && dp[i] < INT_MAX - dp[i - num]) {
                    dp[i] += dp[i - num];
                }
            }
        }
        return dp[target];
    }
};

int main() {
    Solution so;
    vector<int> nums = {1, 2, 3};
    cout << so.combinationSum4(nums, 32) << endl;
    return 0;
}